<?php
namespace app\api\controller;

use think\Db;
use think\Request;

class Homepage extends Base {
    /**
     * @writer:zhouminjin
     * @DateTime:2018-01-15
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 首页接口
     * @return \think\response\Json
     */
    public function info(){
        $post   = request()->post();
        if (!empty($post['user_id'])){
            $city   = Db::table('user')->where('id',$post['user_id'])->value('city');
            $where  = [
                'SE.send_area'        => $city,
                'S.is_open'           => 1,
                'S.check_status'      => 2,
                'D.status'            => 1,
                'P.is_shelves'        => 1,
                'P.status'            => 1,
            ];
        }else{
            $where  = [
                'S.is_open'           => 1,
                'S.check_status'      => 2,
                'D.status'            => 1,
                'P.is_shelves'        => 1,
                'P.status'            => 1,
            ];
        }
        $date   = date('Y-m-d H:i:s');
        $notice = Db::name('discount')
            ->alias('D')
            ->join('supplier S','S.id = D.supplier_id')
            ->join('product P','P.id = D.product_id')
            ->join('supplier_send_manage SE','SE.supplier_id = D.supplier_id')
            ->field('D.*, P.name as product_name')
            ->whereTime('start_time','<',$date)
            ->whereTime('end_time','>',$date)
            ->where($where)
            ->group('D.id')
            ->order('D.id desc')
            ->find();
        if ($notice){
            if ($notice['type'] == 1){
                $notice['name'] = '购买'.$notice['product_name'].'*'.$notice['condition_num'].'减'.$notice['relief_money'];
            }else{
                $notice['name'] = '购买'.$notice['product_name'].'*'.$notice['condition_num'].'送'.$notice['give_product'];
            }
        }
        $banner = Db::name('carousel')->where('status',1)->find();
        if(!empty($banner)){
            $banner = explode(',',$banner['image']);
        }
        $res['status'] = 200;
        $res['notice'] = $notice;
        $res['banner'] = $banner;
        if ($notice){
            $res['msg']    = '获取数据成功';
        }else{
            $res['msg']    = '暂无优惠活动';
        }
        return json($res);
    }

    /**
     * @writer:zhouminjin
     * @DateTime:2018-01-15
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 首页接口
     * @return \think\response\Json
     */
    function getSupplier(){
        $post = request()->post();
        $where = [];
        if($post['cate_id'] !=0 ){
            $where['p.category_id'] = $post['cate_id'];
        }
        if($post['type_id'] !=0 ){
            $where['p.type_id'] = $post['type_id'];
        }

        if($post['small_type_id'] != 0 ){
            $where['p.small_type_id'] = $post['small_type_id'];
        }

        if($post['brand_id'] !=0 ){
            $where['p.brand_id'] = $post['brand_id'];
        }
        $where1 = [];
        if(isset($post['content']) && !empty($post['content'])){
            $where1['s.name|p.name'] = array('like','%'.$post['content'].'%');
        }
        $supplier = Db::name('supplier')->alias('s')
            ->field('s.id,s.send_time_type,s.name,s.business,s.address,s.image')
            ->join('product p','p.supplier = s.id')
            ->join('supplier_send_manage m','m.supplier_id = s.id')
            ->where($where)
            ->where($where1)
            ->where('is_open',1)
            ->where("m.send_area='".$post['city']."' OR m.send_area ='".$post['city']."'")
            ->where('m.flag',1)
            ->where('s.check_status',2)
            ->where('p.status',1)
            ->where('p.is_shelves',1)
            ->limit(($post['page']-1)*5,$post['page']*5)
            ->group('s.id')
            ->select();
        $sql = Db::name('supplier')->getLastSql();
        foreach ($supplier as $key =>$item) {
            $re = Db::name('base_data')->field('name,name_english')->where('flag',1)->whereIn('id',$item['business'])->select();
            $business = [];
            $business_str = '';
            $business_english = [];
            $business_english_str = '';
            foreach ($re as $v) {
                $business[] = $v['name'];
                $business_english[] = $v['name_english'];
            }
            $business_str = implode(',',$business);
            $business_english_str = implode(',',$business_english);
            $supplier[$key]['business'] = $business_str;
            $supplier[$key]['business_english'] = $business_english_str;
            $send = Db::table('supplier_send_manage')
                ->where('supplier_id',$item['id'])
                ->where("send_area='".$post['city']."' OR send_area ='".$post['city']."'")
                ->where('flag',1)
                ->order('month asc')
                ->order('day asc')
                ->select();
            $m = date('m');
            $d = date('d');
            if ($send){
                if($item['send_time_type'] == 1){ //周
                    $week           =   array("一","二","三","四","五","六","日");
                    $week_english   =   array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
                    if(count($send) == 1){
                        $supplier[$key]['date']           = '周'.$week[$send[0]['day']-1];
                        $supplier[$key]['date_english']   = $week_english[$send[0]['day'] -1];
                    }else{
                        $is_choose = false;
                        foreach ($send as $kk => $vv) {
                            $w = date('w');
                            if ($vv['day'] >= $w) {
                                $supplier[$key]['date'][]           = '周'.$week[$vv['day']-1];
                                $supplier[$key]['date_english'][]   = $week_english[$vv['day'] -1];
                                $is_choose = true;
                                //break;
                            }
                        }
                        if(!$is_choose){
                            if(count($re) == 0){
                                $supplier[$key]['date']         = '暂无配送';
                                $supplier[$key]['date_english'] = 'no distribution';
                            }else {
                                $supplier[$key]['date']           = '周'.$week[$send[0]['day']-1];
                                $supplier[$key]['date_english']   = $week_english[$send[0]['day'] -1];
                            }
                        }
                    }
                }else{ //月
                    $month_english=array("","Jan.","Feb.","Mar.","Apr.","May.","Jun.","Jul.","Aug.","Sept.","Oct.","Nov.","Dec.");
                    if(count($send) == 1){
                        if($send[0]['day']>$d && $send[0]['month']>=$m){
                            $supplier[$key]['date']           = $send[0]['month'].'月'.$send[0]['day'].'日';
                            $supplier[$key]['date_english']   = $month_english[$send[0]['month']].$send[0]['day'];
                        }else{
                            $supplier[$key]['date']         = '暂无配送';
                            $supplier[$key]['date_english'] = 'no distribution';
                        }
                    }else {
                        $is_choose = false;
                        foreach ($send as $kkk => $vvv) {
                            if (($vvv['day'] < $d && $vvv['month'] > $m)  ||($vvv['day'] > $d && $vvv['month'] >= $m)){
                                $supplier[$key]['date']           = $send[$kkk]['month'].'月'.$send[$kkk]['day'].'日';
                                $supplier[$key]['date_english']   = $month_english[$send[$kkk]['month']].$send[$kkk]['day'];
                                $is_choose = true;
                                break;
                            }
                        }
                        if(!$is_choose){
                            $supplier[$key]['date']         = '暂无配送';
                            $supplier[$key]['date_english'] = 'no distribution';
                        }
                    }
                }
            }else{
                $supplier[$key]['date']         = '暂无配送';
                $supplier[$key]['date_english'] = 'no distribution';
            }

        }
        if(!empty($supplier)) {
            $res['status'] = 200;
            $res['msg'] = '查询成功';
            $res['supplier'] = $supplier;
        }else{
            $res['status'] = 202;
            $res['msg'] = '暂无数据';
            $res['sql'] = $sql;
        }
        return json($res);
    }
    /**
     * @writer:zhouminjin
     * @DateTime:2018-01-16
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 搜索接口
     * @return array|Json
     */
    public function searchInfo(){
        $post = request()->post();
        $where3 = [];
        if($post['supplier_id'] != 'all'){
            $where3['s.id'] = $post['supplier_id'];
        }
        if(!isset($post['content']) || !isset($post['page'])){
            $res['status'] = 201;
            $res['msg']    = '参数错误';
            return json($res);
        }
        $where = [];
        $where['p.name'] = ['like','%'.$post['content'].'%'];
//        $where2['p.name_english'] = ['like','%'.$post['content'].'%'];
        $re = Db::name('product')->alias('p')
            ->field('p.id as product_id,s.id as supplier_id,p.name as product_name,s.name as supplier_name,p.image,format(ps.price,2) as price,
            ps.packing_proportion,ps.unit,ps.specification')
            ->join('product_specification ps','ps.product_id = p.id')
            ->join('supplier s','s.id = p.supplier')
            ->where('p.status',1)
            ->where('p.is_shelves',1)
            ->where('ps.is_default',1)
            ->where($where3)
            ->where($where)
//            ->whereOr($where2)
            ->select();
        foreach ($re as $k=>$v){
            $time  = date("Y-m-d H:i:s", time());
            $where = [
                'product_id'  => $v['product_id'],
                'status'      => 1,
                'start_time'  => ['<=',$time],
                'end_time'    => ['>=',$time]
            ];
            $count = Db::table('discount')
                ->where($where)
                ->count();
            if ($count>0){
                $re[$k]['is_discount'] = 1;
            }else{
                $re[$k]['is_discount'] = 0;
            }
            $collect = Db::table('user_collect_product')->where(['user_id'=>$post['user_id'],'product_id'=>$v['product_id'],'is_del'=>0])->count();
            if ($collect>0){
                $re[$k]['is_collect'] = 1;
            }else{
                $re[$k]['is_collect'] = 0;
            }
        }
        if(!empty($re)){
            $res['status'] = 200;
            $res['msg']    = '查询成功';
            $res['product']['list'] = $re;
            $res['product']['count'] = count($re);
            $res['sql'] = Db::name('product')->getLastSql();
        }else{
            $res['status'] = 202;
            $res['msm']    = '未查询到数据';
            $res['sql']    = Db::name('product')->getLastSql();
        }
        return json($res);
    }

    public function discountAnn(){
        $post       = request()->post();
        $page       = $post['page'];
        $date       = date('Y-m-d H:i:s');
        if (!empty($post['user_id'])){
            $city = Db::name('user')->where('id',$post['user_id'])->value('city');
            $where  = [
                'se.send_area'        => $city,
                's.is_open'           => 1,
                's.check_status'      => 2,
                'd.status'            => 1,
                'p.is_shelves'        => 1,
                'p.status'            => 1,
            ];
        }else{
            $where  = [
                's.is_open'           => 1,
                's.check_status'      => 2,
                'd.status'            => 1,
                'p.is_shelves'        => 1,
                'p.status'            => 1,
            ];
        }
        $re = Db::name('discount')->alias('d')
            ->field('d.id as discount_id,d.name,d.type,d.condition_num,d.relief_money,d.give_product,p.id as product_id,s.id as supplier_id,s.name as supplier_name,p.name as product_name,p.image')
            ->join('supplier s ','d.supplier_id = s.id')
            ->join('product p','d.product_id = p.id')
            ->join('supplier_send_manage se ','d.supplier_id = se.supplier_id')
            ->whereTime('d.start_time','<',$date)
            ->whereTime('d.end_time','>',$date)
//            ->where('se.send_area',$city)
//            ->where('s.check_status',2)
//            ->where('s.is_open',1)
//            ->where('d.status',1)
            ->where($where)
            ->group('d.id')
            ->order('d.id desc')
            ->limit(($page-1)*10,$page*10)
            ->select();
        if(!empty($re)){
            foreach ($re as $k=>$v){
                if ($v['type'] == 1){
                    $re[$k]['name'] = '购买'.$v['product_name'].'*'.$v['condition_num'].'减'.$v['relief_money'];
                }else{
                    $re[$k]['name'] = '购买'.$v['product_name'].'*'.$v['condition_num'].'送'.$v['give_product'];
                }
            }
            $res['status'] = 200;
            $res['msg']    = '查询成功';
            $res['discount'] = $re;
        }else{
            $res['status'] = 202;
            $res['msg']    = '暂无数据';
        }
        return json($res);
    }

    /**
     * @writer:zhouminjin
     * @DateTime:2018-01-16
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 检测用户是否登录
     * @return array|Json
     */

    public function userCheck(){
        $post = request()->post();
        if(!isset($post['user_id']) || $post['token']){
            $res['status'] = 201;
            $res['msg']    = '参数错误';
            return json($res);
        }
        $user = Db::name('user')->where('id',$post['user_id'])->find();
        if($user['app_token'] == $post['token']){
            $res['status'] = 200;
            $res['msg']    = '检测通过';
        }else{
            $res['status'] = 203;
            $res['msg']    = '检测不通过';
        }
        return json($res);
    }
    /**
     * @writer:zhouminjin
     * @DateTime:2018-01-21
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 获取基础数据
     * @return array|Json
     */
    public function getGoodsType(){
        $goods_type = Db::name('base_data')
            ->where('flag',1)
            ->where('type_menu',1)
//            ->whereIn('id','','')
            ->select();
        $brand = Db::name('base_data')
            ->where('flag',1)
            ->where('type_menu',2)
            ->select();
        if(!empty($goods_type)){
            $res['status'] = 200;
            $res['msg']    = '成功获取种类';
            $res['goods_type'] = $goods_type;
            $res['goods_brand'] = $brand;
        }else{
            $res['status'] = 202;
            $res['msg']    = '成功获取种类';
        }
        return json($res);
    }
    /**
     * @writer:zhouminjin
     * @DateTime:2018-01-21
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 获取基础数据
     * @return array|Json
     */
    public function getSystemSetting(){
        $setting = Db::name('system_setting')->where('flag',1)->select();
        $goods_type = Db::name('base_data')
            ->where('flag',1)
            ->where('type_menu',1)
            ->select();
        $brand = Db::name('base_data')
            ->where('flag',1)
            ->where('type_menu',2)
            ->select();
        if(!empty($goods_type)){
            $res['status'] = 200;
            $res['msg']    = '成功获取种类';
            $res['goods_type'] = $goods_type;
            $res['goods_brand'] = $brand;
            $res['setting']['symbol'] = $setting[1]['value'];
            $res['setting']['tax'] = $setting[0]['value'];
        }else{
            $res['status'] = 202;
            $res['msg']    = '成功获取种类';
        }
        return json($res);
    }
    public function getUser($user_id)
    {
        $re = Db::name('user')->where('id',$user_id)->find();
        if(!empty($re)) {
            $res['status'] = 200;
            $res['msg']    = '查询成功';
            $res['info'] = $re;
        }else{
            $res['status'] = 202;
            $res['msg']    = '数据未空';
        }
        return json($res);
    }
}